package com.intehel.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.intehel.mapper.PermissionMapper;
import com.intehel.mapper.RoleMapper;
import com.intehel.mapper.UserMapper;
import com.intehel.pojo.security.PermissionEntry;
import com.intehel.pojo.security.User;
import com.intehel.service.UserService;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

/**
 * @Description:
 * @Author: Kele
 * @CreateDate: 2022/5/31 17:40
 * @Version:
 */
@Service
public class UserServiceImpl implements UserService {
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private RoleMapper roleMapper;
    @Autowired
    private PermissionMapper permissionMapper;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        User user = userMapper.getUserByUsername(username);
        if (user == null){
            throw new UsernameNotFoundException("用户不存在!");
        }
        user.setRoles(roleMapper.getRoleByUserId(user.getId()));

        List<PermissionEntry> permissions = permissionMapper.getPermissionByUserId(user.getId());
        List<String> codes = permissions.stream().map(PermissionEntry::getCode).collect(Collectors.toList());
        String[] authorities = null;
        if (CollectionUtils.isNotEmpty(codes)) {
            authorities = new String[codes.size()];
            codes.toArray(authorities);
        }
        //身份令牌
        String principal = JSONObject.toJSONString(user);
        return org.springframework.security.core.userdetails.User.withUsername(principal).password(user.getPassword()).authorities(authorities).build();
//        return org.springframework.security.core.userdetails.User.withUsername(principal).password(user.getPassword()).authorities(user.getAuthorities()).build();
    }
}
